const express = require('express');
const md5 = require('blueimp-md5')
const querystring = require('querystring')

// 第三方模块
const svgCaptcha = require('svg-captcha')
const models = require('../db/models')
const shopCarts = require('../data/shopCart')
const indexData = require('../data/index')

const UserModel = models.getModel('user')
const GoodsModel = models.getModel('goods')
const shopCartsModel = models.getModel('shopCarts')
const { randomCode, sendCode } = require('../utils/sms_util')

const users = {}
const _filter = { 'password': 0, '__v': 0} // 查询时过滤

const router = express.Router();

/*
* 账号密码登录
* */
router.post('/login_pwd', (req, res) => {
  const username = req.body.username
  const password = md5(req.body.password)
  const captcha = req.body.captcha.toLowerCase()
  // console.log('/login_pwd', username, password, captcha, req.session);

  // 可以对用户名/密码格式进行检查, 如果非法, 返回提示信息
  if (captcha !== req.session.captcha) {
    return res.send({
      code: 1,
      msg: '验证码不正确'
    })
  }
  // 删除保存的验证码
  delete req.session.captcha

  UserModel.findOne({username}, (err, user) => {
    if (user) {
      // 存在, 则验证信息
      console.log('findUser', user)
      if (user.password !== password) {
        res.send({
          code: 1,
          msg: '用户名或密码不正确!'
        })
      } else {
        req.session.userid = user._id
        res.send({
          code: 0,
          data: {
            _id: user._id,
            username: user.username,
            phone: user.phone
          }
        })
      }
    } else {
      // 不存在， 则存储数据
      const userModel = new UserModel({ username, password })
      userModel.save(function (err, user) {
        // 向浏览器端返回cookie(key=value)
        // res.cookie('userid', user._id, {maxAge: 1000*60*60*24*7})
        req.session.userid = user._id
        const data = {_id: user._id, username: user.username}
        // 3.2. 返回数据(新的user)
        res.send({code: 0, data})
      })
    }
  })
})

/*
* 发送验证码短信
* */
router.get('/sendcode', (req, res, next) => {
  //1. 获取请求参数数据
  const phone = req.query.phone;
  //2. 处理数据
  //生成验证码(6位随机数)
  const code = randomCode(6);
  //发送给指定的手机号
  console.log(`向${phone}发送验证码短信: ${code}`);
  sendCode(phone, code, function (success) {//success表示是否成功
    if (success) {
      users[phone] = code
      console.log('保存验证码: ', phone, code)
      res.send({"code": 0})
    } else {
      //3. 返回响应数据
      res.send({"code": 1, msg: '短信验证码发送失败'})
    }
  })
})

/*
* 一次性图像验证码
* */
router.get('/captcha', (req, res) => {
  let captcha= svgCaptcha.create({
    ignoreChars: '0o1l',
    noise: 2,
    color: true
  })
  req.session.captcha = captcha.text.toLowerCase() // session的存储
  // console.log(req.session.captcha)
  res.type('svg') // 响应的类型
  res.send(captcha.data)
})

/*
* 短信登录
* */
router.post('/login_sms', (req, res) => {
  const { phone, code } = req.body
  console.log('/login_sms', phone, code)
  if (users[phone] !== code) {
    res.send({
      code: 1,
      msg: '手机号或者验证码不正确'
    })
    return
  }
  // 删除保存的code
  delete users[phone]


  UserModel.findOne({phone}, _filter, (err, user) => {
    if (user) {
      // 存在, 则返回对应用户的信息
      req.session.userid = user['_id']
      res.send({
        code: 0,
        data: user
      })
    } else {
      // 不存在, 存储数据
      const userModel = new UserModel({phone})
      userModel.save((err, user) => {
        req.session.userid = user._id
        res.send({
          code: 0,
          data: user
        })
      })
    }
  })
})

/*
* 根据session中的userid, 查询对应的user
* */
router.get('/userinfo', (req, res) => {
  // 取出 userid
  const { userid } = req.session
  console.log(userid);
  // 查询
  UserModel.findOne({_id: userid}, _filter, (err, user) => {
    if (!user) {
      // 不存在, 返回错误信息
      //  清除浏览器保存的 userid 的 cookie
      delete req.session.userid

      res.send({
        code: 1,
        msg: '请您先登录'
      })
    } else {
      // 存在, 返回 user
      res.send({
        code: 0,
        data: user
      })
    }
  })
})

/*
* 用户登出
* */
router.get('/logout', (req, res) => {
  // 清除浏览器保存的userid的cookie
  delete req.session.userid
  // 返回数据
  res.send({code: 0})
})

/*
* 获取商品数据
* */
// const goodsModel = new GoodsModel(goods[0])
// goodsModel.save((err, goods) => {
//   console.log(goods)
// })
router.get('/goods', (req, res) => {
  GoodsModel.find({}, {__v: 0}, (err, goods) => {
    if (!err) {
      res.status(200).json({
        code: 0,
        data: goods
      })
    } else {
      res.status(200).json({
        code: 1,
        msg: '暂时没有商品数据'
      })
    }
  })
})

// 获取购物车数据
// http://localhost:8001/cartgoods?ids=['5d4c2bcc6609620b64caaab9,5d4c2bcc6609620b64caaac0,5d4c2bcc6609620b64caaac4
router.get('/cartgoods/:ids', async (req, res) => {
  // 获取传过来的商品id, 并修改为数组
  let { ids } = req.params
  let idArr  = ids.split(',')

  // 查询数据库
  let result = []
  for (let i = 0; i < idArr.length; i++) {
    let goods = await GoodsModel.findOne({_id: idArr[i]}, { __v: false })
    let newGoods = {
      id: goods._id,
      title: goods.title,
      price: goods.price,
      pic: goods.images[0],
      count: 1,
      inventory_count: goods.inventory_count
    }
    result.push(newGoods)
  }

  if (result.length) {
    res.status(200).json({
      code: 0,
      data: result
    })
  }
})
router.get('/cartgoods', (req, res) => {
  res.send({
    code: 0,
    data: []
  })
})

/*
* 获取首页数据
* */
router.get('/index', (req, res) => {
  res.status(200).json({
    code: 0,
    data: indexData.index
  })
})

/*
* 获取分类数据
* */
router.get('/categories', (req, res) => {
  res.status(200).json({
    code: 0,
    data: indexData.categories
  })
})

module.exports = router;
